class Solution:
    def candy(self, ratings: list) -> int:
        length = len(ratings)
        if length == 0:
            return 0
        res, now_candy, mid, last = 1, 1, 0, 1
        for i in range(1, length):
            if ratings[i] > ratings[i - 1]:
                now_candy += 1
                res += now_candy
                mid, last = 0, now_candy
            elif ratings[i] < ratings[i - 1]:
                now_candy = 1
                mid += 1
                if mid < last:
                    res += mid
                else:
                    res += mid + 1
            else:
                now_candy, last, mid = 1, 1, 0
                res += 1
        return res


a = Solution()
print(a.candy([1, 0, 2]))  # 5
print(a.candy([1, 2, 2]))  # 4
print(a.candy([3, 2, 2, 1, 1]))  # 7
print(a.candy([1, 6, 10, 8, 7, 3, 2]))  # 18
print(a.candy([1, 2, 87, 87, 87, 2, 1]))  # 13
